package com.streambolics.worseminton.servlet;

import java.util.List;
import java.util.TimeZone;

import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;

import com.streambolics.appengine.UserAwareServlet;
import com.streambolics.servlet.RequestBeanSetter;
import com.streambolics.std.HtmlBuilder;
import com.streambolics.std.TimeZoneUtil;
import com.streambolics.worseminton.data.Location;

public class LocationHandler extends UserAwareServlet<Location>
{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    protected Location createNewLocation () throws Exception
    {
        long ownerId = requireIdentifiedPerson ().getId ();
        String name = getParameter ("name");

        // TODO Implement here a method to find the nearest place.

        String query = "select from " + Location.class.getName () + " where ownerId == p_owner && name == p_name";
        Query q = getDatabase ().newQuery (query);
        q.declareParameters ("Long p_owner, String p_name");
        @SuppressWarnings("unchecked")
        List<Location> found = (List<Location>) q.execute (ownerId, name);

        if (found.size () > 0)
        {
            return found.get (0);
        }
        else
        {
            Location l = new Location ();
            l.setName (name);
            l.setOwnerId (ownerId);
            l.setUsed (true);
            save (l);
            return l;
        }
    }

    @Override
    protected void formatBodyAsSimpleDesktopHtml (HtmlBuilder aBuilder, Location aResponseObject) throws Exception
    {
        aBuilder.openDiv ("body");
        aBuilder.openElement ("<h1>");
        aBuilder.addText ("This is location " + aResponseObject.getName ());
        aBuilder.closeElement ("</h1>");
        aBuilder.openForm ("/go/LocationUpdate");
        aBuilder.addHidden ("ID", aResponseObject.getIdAsString ());
        aBuilder.addTextField ("NAME", "Name:", aResponseObject.getName ());
        aBuilder.addBreak ();
        aBuilder.addTextField ("PRICE", "Price for 1 court:", aResponseObject.getCourtPriceAsText ());
        aBuilder.addBreak ();
        aBuilder.addLabel ("TIMEZONE", "normal", "Time zone:");
        String tz = aResponseObject.getTimeZoneName ();
        aBuilder.openCombobox ("TIMEZONE", tz);
        for (TimeZone t : TimeZoneUtil.getAllTimeZones ())
        {
            aBuilder.addComboChoice (t.getID (), t.getID () + " (" + t.getDisplayName () + ")", tz);
        }

        aBuilder.closeCombobox ();
        aBuilder.addRule ();
        aBuilder.addSubmitButton ("OK", "Change");
        aBuilder.closeForm ();
        aBuilder.addAddressForm ("/go/LocationUpdate", aResponseObject.getLatitude (), aResponseObject.getLongitude (), aResponseObject.getAddress (),
                aResponseObject.getIdAsString ());
        aBuilder.closeDiv ();
    }

    @Override
    protected void formatBottomAsSimpleDesktopHtml (HtmlBuilder aBuilder, Location aResponseObject) throws Exception
    {
        aBuilder.openDiv ("bottom");
        aResponseObject.generateNewEventAnchor (aBuilder);
        aBuilder.addText (" | ");
        // TODO : This should go in a "NonHomeServlet"
        aBuilder.addAnchor ("/go/HomeInfo", "Back to home screen");
        super.formatBottomAsSimpleDesktopHtml (aBuilder, aResponseObject);
        aBuilder.closeDiv ();
    }

    @Override
    protected Location generateResponseObject (HttpServletRequest aRequest) throws Exception
    {
        return getReferencedLocation ();
    }

    protected Location getReferencedLocation () throws Exception
    {
        return Location.load (getDatabase (), requireReferenceId ());
    }

    @Override
    protected boolean hasWritePermission (Location aResponseObject)
    {
        return isUser (aResponseObject.getOwnerId ());
    }

    protected void updateLocation (Location aLocation) throws Exception
    {
        if (!requireWritePermission (aLocation))
        {
            return;
        }

        try
        {
            RequestBeanSetter s = new RequestBeanSetter (getRequest (), aLocation);
            s.set ("Name", "NAME");
            s.set ("CourtPrice", "PRICE");
            s.set ("TimeZoneName", "TIMEZONE");
            s.set ("Address", "ADDRESS");
            s.set ("Latitude", "LATITUDE");
            s.set ("Longitude", "LONGITUDE");
        }
        catch (Exception e)
        {
            warnAbout (e);
        }

    }
}
